package com.hsp.homework.test03;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author Stringzhua
 * @Date 2024/4/10 17:34
 * description:文件下载的服务器端
 */
public class Server {
    public static void main(String[] args) throws Exception {
        //1.监听9999端口,等待客户端连接
        ServerSocket serverSocket = new ServerSocket(9999);
        //2.等待客户端连接
        System.out.println("服务端在9999端口监听,等待下载");
        Socket socket = serverSocket.accept();
        //3.读取客户端要下载文件名
        //提示:这里使用while循环读取文件名,是考虑到将来客户端发送的数据较大的情况
        InputStream inputStream = socket.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        String downloadFileName = "";
        while ((len = inputStream.read(b)) != -1) {
            downloadFileName += new String(b, 0, len);
        }
        System.out.println("客户端希望下载的文件名是" + downloadFileName);

        //在服务器上有两个文件,无名.mp3  高山流水.mp3
        //如果客户下载的是高山流水,就返回该文件,否则一律返回无名.mp3
        String resFileName = "";
        if ("高山流水".equals(downloadFileName)) {
            resFileName = "chapter21/src/高山流水.mp3";
        } else {
            resFileName = "chapter21/src/无名.mp3";
        }
        //4.创建一个输入流,读取文件
        BufferedInputStream bis =
                new BufferedInputStream(new FileInputStream(resFileName));
        //5.使用工具类StreamUtils,读取文件到一个字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //6.得到Socket关联的输出流
        BufferedOutputStream bos =
                new BufferedOutputStream(socket.getOutputStream());
        //7.写入到数据通道,返回给客户端
        bos.write(bytes);
//        bos.write(StreamUtils.streamToByteArray(bis));
        socket.shutdownOutput();//很关键,

        //8.关闭相关资源
        bis.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务端退出~");
    }
}
